# -*- coding: utf-8 -*-

import subprocess
import sys
import glob
from logger import *
from config import *

svr_id = str(sys.argv[1])
name = str(sys.argv[2])

code_path = '/home/yt{}/code/'.format(svr_id)
cfg_path = code_path + 'config'
src_path = code_path + 'src'
run_path = code_path + 'run'

# 执行命令并检查错误
try:
    logger.info('syn start')
    # 同步
    logger.info('syn 开始同步')

    subprocess.run(['bash', 'syn_version.sh', svr_id], cwd=python_path)

    # 启服
    logger.info('syn 开始停服')
    subprocess.run(['bash', 'stop_all.sh'], cwd=run_path)
    subprocess.run(['bash', 'rm_core.sh'], cwd=python_path)
    subprocess.run(['bash', 'start_all.sh'], cwd=run_path)

    math_path = run_path + '**/'
    files = glob.iglob(math_path + 'core*')
    if files:
        logger.info('检查检查启服崩溃')
        for file in files:
            logger.error('启服有崩溃 %s', file)
            subprocess.run(['python3', 'error_state.py', svr_id, name, '起服崩溃了，快通知服务器！'], cwd=python_path)
            subprocess.run(['bash', 'ntf_role.sh', svr_id, name], cwd=show_path)
            subprocess.run(['bash', 'start_error.sh', svr_id, name], cwd=show_path)
            sys.exit(1)

    logger.info('syn 起服成功')
    logger.info('syn end')

except subprocess.CalledProcessError as error:
    logger.error('syn ERROR')
    # 在这里可以处理命令执行失败的情况
